package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;



    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */

    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info("新增菜品", dishDto.toString());

        dishService.saveWithFlavor(dishDto);


        return R.success("新增菜品成功");
    }

    @GetMapping("page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();
        //构造条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), Dish::getName, name);
        //排序条件
        queryWrapper.orderByDesc(Dish::getSort);

        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<DishDto> records = new ArrayList<>();
        for (Dish dish : pageInfo.getRecords()) {
            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);

            }
            records.add(dishDto);
        }
//根据上面分页查询结果计算需要的集合对象
       /* List<DishDto>records= pageInfo.getRecords().stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(dish, dishDto);

            //查询分类名称categoryName
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (categoryId != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return  dishDto;

        }).collect(Collectors.toList());*/

        dtoPage.setRecords(records);

        return R.success(dtoPage);

    }

    /**
     * 根据id查询菜品信息，用于页面回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        DishDto dishDto = new DishDto();
        //对象拷贝
        BeanUtils.copyProperties(dish, dishDto);
        //查询当前菜品对应的口味数据sql:select*from dish_flavor where dish_id=?
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        queryWrapper.eq(DishFlavor::getDishId, id);

        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(flavors);

        return R.success(dishDto);

    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info("菜品信息:{}", dishDto);
        dishService.updateDishWithFlavor(dishDto);

        return R.success("菜品修改成功");
    }

    /**
     * 根据条件查询对应菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R <List<DishDto>> list(Dish dish) {
       log.info("菜品条件查询");

       LambdaQueryWrapper<Dish>queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(dish.getCategoryId() !=null,Dish::getCategoryId,dish.getCategoryId());
       queryWrapper.eq(Dish::getStatus,1);

       queryWrapper.orderByAsc(Dish ::getSort).orderByDesc(Dish ::getUpdateTime);

       List<Dish>list=dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            //当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);

            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;

        }).collect(Collectors.toList());


        return R.success(dishDtoList);
    }


    /**
     *
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long>ids) {
        log.info(ids.toString());

        dishService.deleteDishWithFlavor(ids);


        return R.success("删除菜品成功");
    }

    /**
     *
     * 修改启售停售
     * @param sta
     * @param ids
     * @return
     */
    @PostMapping("/status/{sta}")
    public R status(@PathVariable int sta,@RequestParam List<Long> ids){
        ids.stream().map((item)->{
            Dish dish = dishService.getById(item);
            dish.setStatus(sta);
            dishService.updateById(dish);
            return null;
        }).count();

        return R.success("启售停售修改成功");
    }


}
